package db

import (
	syscontext "context"
	"errors"
	"go.uber.org/zap"
	"take-a-break/component/log"
	"xorm.io/xorm"
)

type WeixinOfficialAccount struct {
	ID        int    `json:"id" xorm:"not null pk autoincr comment('自增id') INT"`
	UnionID   string `json:"union_id" xorm:"not null default '' comment('服务号unionid') VARCHAR(40)"`
	OpenID    string `json:"open_id" xorm:"not null default '' comment('服务号openid') VARCHAR(40)"`
	SubTime   int64  `json:"sub_time" xorm:"not null default 0 comment('订阅时间') BIGINT"`
	UnSubTime int64  `json:"un_sub_time" xorm:"not null default 0 comment('取消订阅时间') BIGINT"`
}

// NewWeixinOfficialAccount ...
func NewWeixinOfficialAccount() *WeixinOfficialAccount {
	return new(WeixinOfficialAccount)
}

func (m *WeixinOfficialAccount) Insert(ctx syscontext.Context, session *xorm.Session) (ok bool, err error) {
	if session == nil {
		session = GetMasterDbSession(ctx)
	}
	var row int64
	row, err = session.Insert(m)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("新增用户关注公众号失败", zap.Error(err))
		err = errors.New("系统出错,新增用户关注公众号失败")
	}
	if row > 0 {
		ok = true
	}
	return
}

func (m *WeixinOfficialAccount) GetByUnionID(ctx syscontext.Context, session *xorm.Session, unionID string) (exists bool, oa *WeixinOfficialAccount, err error) {
	if session == nil {
		session = GetSlaveDbSession(ctx)
	}
	oa = new(WeixinOfficialAccount)
	_, err = session.Where("union_id=?", unionID).Get(oa)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("根据用户微信id获取公众号数据", zap.Error(err))
		err = errors.New("系统出错,根据用户微信id获取公众号数据")
	}
	if oa.ID > 0 {
		exists = true
	}
	return
}

func (m *WeixinOfficialAccount) Update(ctx syscontext.Context, session *xorm.Session, unionID string, clos ...string) (err error) {
	if session == nil {
		session = GetSlaveDbSession(ctx)
	}
	if len(unionID) <= 0 {
		err = errors.New("unionid 不存在")
		return
	}
	if len(clos) > 0 {
		session = session.Cols(clos...)
	}
	_, err = session.Where("union_id=?", unionID).Update(m)
	if err != nil {
		ck_log.LogCtx(ctx).Errorw("修改用户公众号数据", zap.Error(err))
		err = errors.New("系统出错,修改用户公众号数据")
	}
	return
}

func (m *WeixinOfficialAccount) InsertOrUpdate(ctx syscontext.Context, session *xorm.Session, openID, unionID string, subTime int64) (err error) {
	if session == nil {
		session = GetMasterDbSession(ctx)
	}
	exists, m1, err := m.GetByUnionID(ctx, session, unionID)
	if err != nil {
		return
	}
	if !exists {
		m2 := &WeixinOfficialAccount{
			UnionID:   unionID,
			OpenID:    openID,
			SubTime:   subTime,
			UnSubTime: 0,
		}
		_, err = m2.Insert(ctx, session)
	} else {
		m1.SubTime = subTime
		m1.UnSubTime = 0
		err = m1.Update(ctx, session, unionID, "sub_time", "un_sub_time")
	}
	return
}
